package com.czq.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czq.common.utils.PageUtils;
import com.czq.common.utils.Query;

import com.czq.mall.product.dao.CategoryDao;
import com.czq.mall.product.entity.CategoryEntity;
import com.czq.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> queryTree() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> level1List = categoryEntities.stream()
                .filter(e -> e.getParentCid() == 0)
                .peek(e-> e.setChildren(getChildern(e,categoryEntities)))
                .collect(Collectors.toList());

        return level1List;
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        // List<CategoryEntity> categoryEntities = baseMapper.selectBatchIds(ids);

        baseMapper.deleteBatchIds(ids);
    }

    private List<CategoryEntity> getChildern(CategoryEntity categoryEntity, List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream()
                .filter(e -> categoryEntity.getCatId().equals(e.getParentCid()))
                .peek(e -> e.setChildren(getChildern(e, all)))
                .sorted(Comparator.comparingInt(CategoryEntity::getSort)).collect(Collectors.toList());
        return collect;
    }
}